import {
  ApiRootUrl,
  apiList
} from '../../../config/index.js'
import Dialog from '../../../@vant/weapp/dialog/dialog';
import {
  IMG_PATH
} from '../../../config/index.js'
import {
  request,judgeData,formatDateTime,formatStringTime
} from "../../../utils/util.js"
import Toast from '../../../@vant/weapp/toast/toast';
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    IMG_PATH: IMG_PATH,
    tongzhiShow: false,
    allpendingchecked: false,
    allpendingTap: false,
    allchecked: false,
    height: 0,
    canTap: false, //可以点击按钮
    tongzhimessage: '',
    height: 0,
    determineList: [],
    pendingList: [],
    passList: [],
    minDate: new Date(2020, 0, 1).getTime(),
    maxDate: new Date().getTime(),
    sourceShow: false,
    dangerShow: false,
    timeshow: false,
    leaveTimeStart: "",
    leaveTimeEnd: "",
    statusBarHeight: '',
    active: 0,
    searchValue: '',
    sourceName: "劳务公司",
    orgCode:"",
    time: '选择时间',
    danger: '备案登记',
    dangerId: "",
    noticeType: 0,
    noticeTabType: 0,
    sourceShowColumns: [],
    dangerShowColumns: [{
      id: '',
      text: '全部'
    },{
      id: '0',
      text: '未提交'
    }, {
      id: '1',
      text: '已提交'
    }, {
      id: '2',
      text: '备案中'
    }, {
      id: '3',
      text: '已备案'
    }],
    tabList: [{
      id: 0,
      title: '待面试',
    }, {
      id: 1,
      title: '通过',
    }, {
      id: 2,
      title: '待定',
    }],
    userinfo:{},
  },
  companyClick() {
    this.setData({
      sourceShow: true
    })
  },
  dangerShowClose() {
    this.setData({
      dangerShow: false
    })
  },
  dangerClick() {
    this.setData({
      dangerShow: true
    })
  },
  sourceShowClose() {
    this.setData({
      sourceShow: false
    })
  },
  dangerShowConfirm(event) {
    this.setData({
      danger: event.detail.value.text,
      dangerId: event.detail.value.id,
      dangerShow: false
    }, () => {
      this.getInterview()
    })
  },
  timeClick() {
    this.myComponent.showPicker()
    this.setData({
      timeshow: true
    })
  },
  sourceShowConfirm(event) {
    let text = event.detail.value.text
    if(text == "全部"){
      text ="劳务公司"
    }
    this.setData({
      sourceName: text,
      orgCode:event.detail.value.id,
      sourceShow: false
    },()=>{
      this.getInterview()
    })
  },
  tabClick(event) {
    this.setData({
      active: event.detail.index,
      pageNumber:1
    }, () => {
      this.getInterview()
    })
  },
  backClick(event) {
    wx.navigateBack();
    // console.log(event);
    // Dialog.confirm({
    //   title: '返回',
    //   message: '请确认是否返回？',
    // }).then(() => {
    //   wx.navigateBack();
    // }).catch(() => {
    //   console.log('取消')
    // });
  },

  formatDate(date) {
    var date = new Date(date);
    var YY = date.getFullYear() + '-';
    var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
    return YY + MM + DD;
  },
  formateTime(time){
    let arr = time.split("-")
    return arr[0]+arr[1]+arr[2]+""
  },
  selectStart(e){
    let time = this.formateTime(e.detail)
    console.log("开始时间",e)
    this.setData({
      time: `${e.detail} - ${this.data.leaveTimeEnd}`,
      leaveTimeStart:time
    })
  },
  selectEnd(e){
    let time = this.formateTime(e.detail)
    console.log("结束时间",e)
    this.setData({
      time: `${this.data.leaveTimeStart} - ${e.detail}`,
      leaveTimeEnd:time
    })
  },
  getRangeTime(e){
    let beginTime = formatDateTime(e.detail.begin);
    let endTime =formatDateTime(e.detail.end);
    console.log(beginTime,endTime)
    this.setData({
      leaveTimeStart:formatStringTime(beginTime),
      leaveTimeEnd:formatStringTime(endTime),
      isRange:true
    })
  },
  timeConfirm(event) {
    // const [start, end] = event.detail;
    let beginTime = this.data.leaveTimeStart
    let endTime = this.data.leaveTimeEnd
    let time = beginTime+"-"+endTime
    if(!this.data.isRange){
      beginTime = "";
      endTime = "";
      time="选择时间"
    }
    this.setData({
      timeshow: false,
      leaveTimeStart:beginTime,
      leaveTimeEnd:endTime,
      time:time,
      isRange:false
    },()=>{
      this.getInterview()
    });
    this.myComponent.hidePicker()

  },

  getJobStatus(vlaue) {
    let index = Number(vlaue)
    let returnValue;
    switch (index) {
      case 0:
        returnValue = 0;
        break;
      case 1:
        returnValue = 2;
        break;
      case 2:
        returnValue = 1;
        break;
      default:
        returnValue = 0;
        break;
    }
    return returnValue
  },
  getInterview() {
    let jobStatus = this.getJobStatus(this.data.active)
    let surveyStatus;
    if(Number(this.data.active) == 1){
      surveyStatus = this.data.dangerId == "" ? "" : Number(this.data.dangerId)
    }else{
      surveyStatus=""
    }
    console.log("=====>",jobStatus)
    let params = {
      // labourName: this.data.sourceName == "劳务公司" ? "":this.data.sourceName,
      // labourName: "劳务公司",
      labourCode:this.data.orgCode,
      name: this.data.searchValue,
      phone: "",
      beginTime:this.data.leaveTimeStart,
      endTime:this.data.leaveTimeEnd,
      surveyStatus: surveyStatus,
      jobStatus: jobStatus,
      flag:jobStatus == 0 ? 1:""
      // jobStatus: 3,
    }
    Toast.loading({
      message: '加载中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    request(apiList.waitInterview, params).then((res) => {
      let arr = []
      for (let i = 0; i < res.data.length; i++) {
        res.data[i].checked = false
        arr.push(res.data[i])
      }
      if (Number(this.data.active) == 0) {
        this.setData({
          pendingList: arr
        })
      } else if (Number(this.data.active) == 1) {

        this.setData({
          passList: arr
        })
      } else if (Number(this.data.active) == 2) {
        this.setData({
          determineList: arr
        })
      }
      this.setData({
        canTap:false
      })
      Toast.clear();
    }).catch((err) => {
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  checkJob(id,status,message){
    if(id.length == 0){
      Toast("请选择人员")
      return
    }
    let params = {
      idList:id,
      jobStatus:status,
      remark:message
    }
    console.log("params===>",params)
    Toast.loading({
      message: '处理中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    request(apiList.checkJob,params).then((res) => {
      console.log("请求结果=====>",res)
      Toast.clear();
      wx.showToast({
        title: '处理成功',
      })
      this.setData({
        tongzhiShow: false,
        tongzhimessage: "",
      })
      this.getInterview()
    }).catch((err) => {
      this.setData({
        tongzhiShow: false,
      })
      console.log("err==>",err)
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  refendClick(event) {
    console.log(event);
    this.setData({
      tongzhiShow: true
    })
  },
  sendClick() {
    let message = this.data.tongzhimessage;
    this.handlePending(message)
    
  },
  handlePending(message){
    let type = this.data.noticeType
    let ids=[];
    let id = [];
    if(this.data.active == 0){
      for(let i=0;i<this.data.pendingList.length;i++){
        if(this.data.pendingList[i].checked){
          let obj = {
            id:this.data.pendingList[i].id,
            openId:this.data.pendingList[i].openId,
            componentCode:this.data.pendingList[i].componentCode,
            surveyStatus:"1",
          }
          ids.push(obj)
          id.push(this.data.pendingList[i].id)
        }
      }
    }else if(this.data.active == 2){
      for(let i=0;i<this.data.determineList.length;i++){
        if(this.data.determineList[i].checked){
          let obj = {
            id:this.data.determineList[i].id,
            openId:this.data.determineList[i].openId,
            componentCode:this.data.determineList[i].componentCode,
            surveyStatus:"1",
          }
          ids.push(obj)
          id.push(this.data.determineList[i].id)
        }
      }
    }
    
    if(type == 0){
      this.checkJob(id,2,message)
    }else if(type == 1){
      this.checkJob(id,6,message)
    }else if(type == 2){
      this.checkJob(id,1,message)
      // this.checkLabal(ids)
    }
  },
  refendallClick(e) {
    let type = Number(e.currentTarget.dataset.type)
    this.setData({
      tongzhiShow:true,
      noticeType: type,
    })
  },
  // refendpendingClick(event) {
  //   console.log(event);
  // },
  checkLabal(ids){
    let params = {
      ids:ids,
      flag:"1",
    }
    Toast.loading({
      message: '处理中...',
      mask: true,
      duration: 0,
      forbidClick: true,
    });
    request(apiList.checkLabor,params).then((res) => {
      console.log("请求结果=====>",res)
      Toast.clear();
      wx.showToast({
        title: '审核成功',
      })
      this.getInterview()
    }).catch((err) => {
      console.log("err==>",err)
      Toast.clear();
      Toast({
        duration: 3000,
        forbidClick: true,
        type: 'fail',
        message: err.message,
      });
    })
  },
  pendingChange(event) {
    let id = event.target.dataset.id;
    let dataList = this.data.determineList;
    dataList.forEach((item) => {
      if (item.id == id) {
        item.checked = event.detail
      }
    })
    let flag = true;
    for (let i = 0; i < dataList.length; i++) {
      if (!dataList[i].checked) {
        flag = false
      }
    }
    this.setData({
      allpendingchecked: flag,
      determineList: dataList
    })
    let list = dataList.map(value => value['checked']);
    if (list.includes(true)) {
      this.setData({
        canTap: true
      })
    } else {
      this.setData({
        canTap: false
      })
    }
  },
  pendingDetailsClick(event) {
    console.log('待面试');
    console.log(event);
    wx.navigateTo({
      url: `../pendingdetails/pendingdetails?id=${event.target.dataset.id}&type=${true}&requestType=${event.target.dataset.type}&ids=${event.target.dataset.ids}`
    })
  },
  clear(){
    this.setData({
      searchValue:""
    },()=>{
      this.getInterview()
    })
    
  },
  pendingDetailsClick1(event){
    console.log('通过');
    console.log(event)
    let id = event.currentTarget.dataset.id;
    let ids = event.currentTarget.dataset.ids;
    let type = event.currentTarget.dataset.type
    // wx.navigateTo({
    //   url: `../detail/detail?id=${id}&type=${type}`,
    // })
    wx.navigateTo({
      url: `../pendingdetails/pendingdetails?id=${id}&type=${true}&requestType=${type}&ids=${ids}&isTongguo=${1}`
    })
  },
  refendpendingClick(event) {
    wx.navigateTo({
      url: `../pendingdetails/pendingdetails?id=${event.target.dataset.id}&type=${false}&requestType=${event.target.dataset.type}&ids=${event.target.dataset.ids}`
    })
  },
  passChange1(event){
    let id = event.target.dataset.id;
    let dataList = this.data.pendingList;
    dataList.forEach((item) => {
      if (item.id == id) {
        item.checked = event.detail
      }
    })
    let flag = true;
    for (let i = 0; i < dataList.length; i++) {
      if (!dataList[i].checked) {
        flag = false
      }
    }
    this.setData({
      allchecked: flag,
      pendingList: dataList
    })
    let list = dataList.map(value => value['checked']);
    if (list.includes(true)) {
      this.setData({
        canTap: true
      })
    } else {
      this.setData({
        canTap: false
      })
    }
  },
  passChange(event) {
    let id = event.target.dataset.id;
    let dataList = this.data.passList;
    dataList.forEach((item) => {
      if (item.id == id) {
        item.checked = event.detail
      }
    })
    console.log("-->", dataList)
    let flag = true;
    for (let i = 0; i < dataList.length; i++) {
      if (!dataList[i].checked) {
        flag = false
      }
    }
    this.setData({
      allchecked: flag,
      passList: dataList
    })
    let list = dataList.map(value => value['checked']);
    if (list.includes(true)) {
      this.setData({
        canTap: true
      })
    } else {
      this.setData({
        canTap: false
      })
    }
  },
  timeClose() {
    this.myComponent.hidePicker()
    this.setData({
      timeshow: false,
      isRange:false,
    });
  },
  defalut() {
    //触发简历初始化，去除默认选择项
    const child = this.selectComponent('#Calendar');
    const child1 = this.selectComponent('#Calendar1');
    child.resetToday()
    child1.resetToday()
  },
  timeAll() {
    this.defalut()
    this.setData({
      timeshow: false,
      leaveTimeStart: "",
      leaveTimeEnd: "",
      time: "选择时间"
    }, () => {
      this.getInterview();
    });
  },
  getSearchValue(e) {
    let value = e.detail;
    this.setData({
      searchValue: value
    }, () => {
      this.getInterview()
    })
  },
  pendingallChange(event) {
    let dataList = this.data.determineList;
    dataList.forEach((item) => {
      item.checked = event.detail;
    })
    this.setData({
      allpendingchecked: event.detail,
      determineList: dataList
    })
  },
  passallChange(event) {
    let dataList = this.data.passList;
    dataList.forEach((item) => {
      item.checked = event.detail;
    })
    this.setData({
      allchecked: event.detail,
      canTap: event.detail,
      passList: dataList
    })
  },
  tongzhiClose() {
    this.setData({
      tongzhiShow: false,
      tongzhimessage: ''
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let query = wx.createSelectorQuery();
    query.select('.content').boundingClientRect(rect => {
      let height = rect.height;
      this.setData({
        statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],
        height: wx.getSystemInfoSync().windowHeight - height,
        sourceShowColumns: app.globalData.companyList||[],
        userinfo:wx.getStorageSync('userinfo')
      })
    }).exec();
    this.myComponent = this.selectComponent('#timeRangeComponent')
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getInterview()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})